<?php

Yii::import('application.vendors.*');
require_once('Zend/Loader.php');

class ItemController extends RController
{

    public function init()
    {
        parent::init();
        $baseUrl = Yii::app()->baseUrl;
        $cs = Yii::app()->getClientScript();
        $cs->registerScriptFile($baseUrl . '/js/bootstrap-fileupload.min.js');
        $cs->registerCssFile($baseUrl . '/css/bootstrap-fileupload.min.css');
    }

    public function actionIndex()
    {
        $this->render('index');
    }

    public function actionTestBarCode()
    {
        Zend_Loader::loadClass('Zend_Barcode');
        Zend_Loader::loadClass('Zend_Barcode_Object_Code39');
        Zend_Loader::loadClass('Zend_Barcode_Renderer_Image');
        Zend_Loader::loadClass('Zend_Validate_Barcode_Code39');
        $barcodeOptions = array('text' => '001');
        // No required options
        $rendererOptions = array();

        // Draw the barcode in a new image,
        // send the headers and the image
        Zend_Barcode::factory(
                'code39', 'image', $barcodeOptions, $rendererOptions
        )->render();
    }

    public function actionList()
    {
        $searchFormData = isset($_POST['SearchForm']) ? $_POST['SearchForm'] : array();
        $searchForm = new SearchForm();
        $searchForm->setAttributes($searchFormData);
        $data = $searchForm->getAttributes();
        $keyword = isset($data['keyword']) ? $data['keyword'] : '';

        $criteria = new CDbCriteria();
        $condition = array();
        if (!empty($keyword)) {
            $condition[] = "MATCH (features) AGAINST ('$keyword' IN BOOLEAN MODE)";
        }

        $product_id = Yii::app()->getRequest()->getQuery('product_id');
        if (!empty($product_id)) {
            $condition[] = 'product_id = ' . (int) $product_id;
        }
        if ($condition) {
            $criteria->condition = implode(' AND ', $condition);
        }
        $dataProvider = new CActiveDataProvider('Item', array(
                    'criteria' => $criteria
                ));

        $this->breadcrumbs = array(
            'Mặt hàng' => array('/product/item/index'),
            'Danh sách mặt hàng'
        );

        $this->render('list', array(
            'dataProvider' => $dataProvider
        ));
    }

    public function actionView()
    {
        $id = Yii::app()->getRequest()->getQuery('id');
        $model = Item::model()->with('product')
                ->with('supplier')
                ->findByPk($id);

        $this->breadcrumbs = array(
            'Mặt hàng' => array('/product/item/list'),
            'Chi tiết mặt hàng'
        );

        $this->render('view', array(
            'model' => $model
        ));
    }

    private function _handleCreateUpdate($message, $is_update = false)
    {
        $model = new Item();

        if ($is_update) {
            $id = Yii::app()->getRequest()->getQuery('id');
            $model = Item::model()->findByPk($id);
        }

        if (isset($_POST['Item'])) {
            if (isset($_POST['Item']['quantity'])) {
                unset($_POST['Item']['quantity']);
            }
            $model->setAttributes($_POST['Item']);

            $model->features = $model->title . ';' .
                    $model->size . ';' .
                    $model->color . ';' .
                    $model->material;

            if ($model->validate() && $model->save()) {
                Yii::app()->user->setFlash('success', $message);
            } else {
                Yii::app()->user->setFlash('error', 'Có lỗi xảy ra');
            }
        }

        $this->render('_form', array(
            'model' => $model,
        ));
    }

    public function actionCreate()
    {
        $this->breadcrumbs = array(
            'Mặt hàng' => array('/product/item/list'),
            'Tạo mặt hàng mới'
        );

        $message = 'Bạn đã thêm mặt hàng mới thành công';
        $this->_handleCreateUpdate($message);
    }

    public function actionUpdate()
    {
        $this->breadcrumbs = array(
            'Mặt hàng' => array('/product/item/list'),
            'Cập nhật mặt hàng'
        );

        $message = 'Bạn đã cập nhật mặt hàng thành công';
        $this->_handleCreateUpdate($message, true);
    }

    public function actionDelete()
    {
        $id = Yii::app()->getRequest()->getQuery('id');
        $model = Item::model()->findByPk($id);
        $model->delete();
    }

    public function actionImportExcel()
    {
        $model = new ImportExcelForm();
        if (isset($_FILES['ImportExcelForm'])) {
            $model->attributes = $_FILES['ImportExcelForm'];
            $model->xfile = CUploadedFile::getInstance($model, 'xfile');
            $path = '';
            if ($model->xfile != null) {
                $path = Yii::app()->basePath . '/../upload/' . $model->xfile;
                $model->xfile->saveAs(Yii::app()->basePath . '/../upload/' . $model->xfile);
                $this->redirect(array('/product/item/import-excel-review', 'file' => base64_encode($model->xfile)));
            }
        }

        $this->render('import-excel', array(
            'model' => $model,
        ));
    }

    public function actionImportExcelReview()
    {
        $file = Yii::app()->getRequest()->getQuery('file');
        Yii::import('ext.phpexcel.XPHPExcel', true);
        $path = Yii::app()->basePath . '/../upload/' . base64_decode($file);
        $objPHPExcel = XPHPExcel::load($path);
        $data = array();
        foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
            $highestRow = $worksheet->getHighestRow();
            $highestColumn = $worksheet->getHighestColumn();
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
            for ($row = 1; $row <= $highestRow; ++$row) {
                $sub = array();
                for ($col = 0; $col < $highestColumnIndex; ++$col) {
                    $cell = $worksheet->getCellByColumnAndRow($col, $row);
                    $val = $cell->getValue();
                    $sub[] = $val;
                }
                $data[] = $sub;
            }
        }
        //ID|Mặt hàng|Mã sản phẩm|Sản phẩm|Nhà cung cấp|Giá|Số lượng|Size|Màu sắc|Chat lieu
        if (isset($_POST['save'])) {
            $rows = array_slice($data, 1); //remove first title row
            $errors = array();
            foreach ($rows as $row) {

                $product_id = Product::model()->findIDByTitle($row[3]);
                $supplier_id = Supplier::model()->findIDByName($row[4]);
                
                $item = Item::model()->findByPk($row[0]);
                
                if ($item == null) {
                    $item = new Item;
                }
                
                $item->title = $row[1];
                $item->code = $row[2];
                $item->product_id = $product_id;
                $item->supplier_id = $supplier_id;
                $item->price = $row[5];
                $item->quantity = $row[6];
                $item->size = $row[7];
                $item->color = $row[8];
                $item->material = $row[9];
                $result = $item->save();
                if (!$result) {
                    $errors[] = 1;
                } else {
                    $errors[] = 0;
                }
            }
            if (in_array(1, $errors)) {
                Yii::app()->user->setFlash('error', 'Có lỗi xảy ra');
            } else {
                Yii::app()->user->setFlash('success', 'Bạn đã nhập dữ liệu thành công');
            }
        }

        $this->render('import-excel-review', array(
            'data' => $data,
        ));
    }

    public function actionDownloadExcel()
    {
        $this->layout = false;
        $rows = Item::model()->with('product')->with('supplier')->findAll();

        Yii::import('ext.phpexcel.XPHPExcel', true);
        $objPHPExcel = XPHPExcel::createPHPExcel();

        // Add some data
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'ID');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Mặt hàng');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Mã sản phẩm');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'Sản phẩm');
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', 'Nhà cung cấp');
        $objPHPExcel->getActiveSheet()->SetCellValue('F1', 'Giá');
        $objPHPExcel->getActiveSheet()->SetCellValue('G1', 'Số lượng');
        $objPHPExcel->getActiveSheet()->SetCellValue('H1', 'Size');
        $objPHPExcel->getActiveSheet()->SetCellValue('I1', 'Màu sắc');
        $objPHPExcel->getActiveSheet()->SetCellValue('J1', 'Chất liệu');

        for ($i = 0; $i < sizeof($rows); $i++) {
            $index = $i + 2;
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $index, $rows[$i]->item_id);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $index, $rows[$i]->title);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $index, $rows[$i]->code);
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $index, $rows[$i]->product['title']);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $index, $rows[$i]->supplier['name']);
            $objPHPExcel->getActiveSheet()->SetCellValue('F' . $index, $rows[$i]->price);
            $objPHPExcel->getActiveSheet()->SetCellValue('G' . $index, $rows[$i]->quantity);
            $objPHPExcel->getActiveSheet()->SetCellValue('H' . $index, $rows[$i]->size);
            $objPHPExcel->getActiveSheet()->SetCellValue('I' . $index, $rows[$i]->color);
            $objPHPExcel->getActiveSheet()->SetCellValue('J' . $index, $rows[$i]->material);
        }
        // Rename sheet
        $objPHPExcel->getActiveSheet()->setTitle('Danh sach mat hang');


        // Save Excel 2007 file
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="DanhSachMatHang' . date('d-M-Y') . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter->save('php://output');
        Yii::app()->end();
    }

    public function actionImport()
    {
        $id = Yii::app()->getRequest()->getQuery('id');
        $model = Item::model()->findByPk($id);
        /* @var $model Item */
        if (isset($_POST['Item'])) {
            $data = $_POST['Item'];
            $model->addQuantityAndPrice(
                    $data['quantity'], $data['price']
            );
            $this->redirect(array('view', 'id' => $model->item_id));
        }
        $this->render('import', array(
            'model' => $model,
        ));
    }

    public function actionHistory()
    {
        $id = Yii::app()->getRequest()->getQuery('id');
        $criteria = new CDbCriteria();
        $criteria->compare('item_id', $id);

        $dataProvider = new CActiveDataProvider('Inventory', array(
                    'criteria' => $criteria
                ));

        $this->breadcrumbs = array(
            'Mặt hàng' => array('/product/item/list'),
            'Cập nhật mặt hàng' => array('/product/item/update/id/' . $id),
            'Xem lịch sử các lần nhập'
        );
        $this->render('history', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function filters()
    {
        return array(
            'rights'
        );
    }

}